package com.simplegovern.start;

import java.util.List;
import java.util.Set;

import com.simpleframe.env.EnvionmentStartup;
import com.simpleframe.env.Environment;
import com.simpleframe.security.Action;
import com.simpleframe.security.AuthorityContext;
import com.simpleframe.security.Module;
import com.simpleframe.security.Role;
import com.simplegovern.authority.SysAction;
import com.simplegovern.authority.SysActiontype;
import com.simplegovern.authority.SysRole;
import com.simplegovern.authority.SysRoleAction;
import com.simplegovern.authority.action.RoleAction;
import com.simplegovern.authority.service.ActionService;
import com.simplegovern.authority.service.ActiontypeService;
import com.simplegovern.authority.service.RoleActionService;
import com.simplegovern.authority.service.RoleService;

public class AuthorityCacheStartUp implements EnvionmentStartup {

	private ActiontypeService actiontypeService = Environment.getContext()
			.getBean(ActiontypeService.class);
	private RoleService roleService = Environment.getContext().getBean(
			RoleService.class);
	private RoleActionService roleActionService = Environment.getContext().getBean(
			RoleActionService.class);

	public void execute() throws Exception {
		System.out.println("==== 后台 加载权限缓存开始 =====");
		// //将系统所有的操作权限取出来
		List<SysActiontype> actiontypes = actiontypeService.getActiontypes();
		// //将系统所有的用户角色取出来
		// List<com.zhidian3g.model.authority.domain.Role> roleList =
		// roleService.getRoleList();
		// if(actionList != null) {
		for (SysActiontype type : actiontypes) {
			Module module = new Module();
			module.setId(String.valueOf(type.getId()));
			module.setName(type.getName());
			Set<SysAction> actions = type.getSysActions();
			for (SysAction sa : actions) {
				Action action = new Action();
				action.setId(String.valueOf(sa.getId()));
				action.setName(sa.getName());
				action.setUrl(sa.getUrl());
				module.addAction(action);
			}
			AuthorityContext.addModule(module);
		}

		List<SysRole> roles = roleService.getRoles();
		for (SysRole sr : roles) {
			roleService.addRoleCache(sr);
		}
		// }
		// if(roleList != null) {
		// for(com.zhidian3g.model.authority.domain.Role role : roleList) {
		// //将角色存放到内存中
		// addRole(role);
		// }
		// }

		System.out.println("==== 后台 加载权限缓存结束 =====");
	}
}
